# -*- conding:UTF-8 -*-

'''
@ Project: p7_flask
@ File: channel.py
@ Author: 师路遥
@ Date：2022/6/7 13:01

'''
import json
from flask import Blueprint,jsonify
from flask_restful import reqparse,Api,Resource,marshal
from common.model_fields.user import *
from models.user import *

channel_bp = Blueprint('channel_bp',__name__,url_prefix='/news')

api = Api(channel_bp)

class ChannelAll(Resource):
    def get(self):
        channel = Channel.query.all()
        data = marshal(channel,channel_fields)
        return data

class NewsBasic(Resource):
    def get(self):
        parse = reqparse.RequestParser()
        parse.add_argument('category')
        args = parse.parse_args()
        cid = args['category']
        print('>>>>>>>>',cid)
        try:
            # 通过 cid 查询到频道
            chennel = Channel.query.filter_by(cid=cid).first()
            # 反向查询 所有的文章
            basics = chennel.news
            data = marshal(basics, news_fields)
            print("123456123456", data)
        except Exception as e:
            print("查询频道下的文章报错", e)
            return jsonify(msg="查询失败", code=200)
        datas = json.loads(json.dumps(data))
        # 给每篇文章添加作者
        basic_list = []
        for i in datas:
            user = UserModel.query.filter_by(uid=i['user_id']).first()
            i['user_name'] = user.uname
            basic_list.append(i)
        print("11111111111>>>", basic_list)
        return jsonify(msg="查询成功", code=200, data=basic_list)


api.add_resource(NewsBasic,'/channels')
api.add_resource(ChannelAll,'/category')